<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="dialogTitle"
    width="500"
    @close="handleClose"
  >
    <el-form
      :model="formData"
      ref="formRef"
      :rules="rules"
      label-position="right"
      label-width="80px"
      size="default"
      :scroll-to-error="true"
      :show-message="false"
    >
      <el-form-item
        label="上级部门"
        prop="pid"
        class="required label-right-align"
        label-width="120px"
      >
        <el-tree-select
          v-model="formData.pid"
          :data="department_options"
          :default-expand-all="true"
          :expand-on-click-node="false"
          :check-strictly="true"
          style="width: 240px"
          :check-on-click-node="true"
          filterable
          :props="{ label: 'title', value: 'id' }"
        />
      </el-form-item>
      <el-form-item
        label="部门名称"
        prop="title"
        class="required label-right-align"
        label-width="120px"
      >
        <el-input v-model="formData.title" type="text" clearable></el-input>
      </el-form-item>
      <el-form-item
        label="部门经理"
        prop="manager"
        class="label-right-align"
        label-width="120px"
      >
        <el-select
          v-model="formData.manager"
          filterable
          remote
          placeholder="输入用户ID/昵称/姓名/手机号进行搜索"
          remote-show-suffix
          :remote-method="searchUser"
          :loading="search_loading"
          style="width: 240px"
          default-first-option
        >
          <el-option
            v-for="item in userOptions"
            :key="item.user_id"
            :label="item.real_name ? item.real_name : item.nickName"
            :value="item.user_id"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="排序"
        prop="sort"
        class="label-right-align"
        label-width="120px"
      >
        <el-input-number
          v-model="formData.sort"
          controls-position="right"
          :min="0"
          :max="1000"
          :precision="0"
          :step="1"
        ></el-input-number>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogClose">关闭</el-button>
        <el-button type="primary" @click="submitForm"> 提交 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, defineExpose, defineEmits, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { getUserOption } from "@/api/user";
import {
  addDepartment,
  editDepartment,
  getDepartmentForm,
  getDepartmentOptionsApi,
} from "@/api/company/department";
const dialogFormVisible = ref(false);
const formRef = ref(null);
const department_parent_Options = ref([]);
const dialogType = ref("add");
const dialogTitle = ref("");
const formData = ref({
  id: 0,
  pid: 0,
  title: "",
  manager: "",
  sort: 0,
});

const rules = reactive({
  title: [
    {
      required: true,
      message: "请输入部门名称",
    },
  ],
});

const search_loading = ref(false);
const userOptions = ref<any[]>([]);
const department_options = ref<any[]>([]);
const searchUser = (query: string) => {
  if (query !== "") {
    search_loading.value = true;
    getUserOption({
      keyword: query,
    }).then((res: any) => {
      if (res.code == 1) {
        userOptions.value = res.data;
        search_loading.value = false;
      }
    });
  } else {
    userOptions.value = [];
  }
};

function addSave() {
  addDepartment(formData.value)
    .then((res) => {
      ElMessage.success("添加成功");
      getTableList();
      dialogClose();
    })
    .catch((err) => {});
}
function editSave() {
  editDepartment(formData.value)
    .then((res) => {
      ElMessage.success("编辑成功");
      getTableList();
      dialogClose();
    })
    .catch((err) => {});
}
function getInfo(id) {
  getDepartmentForm(id)
    .then((res: any) => {
      if (res.code == 1) {
        formData.value = res.data;
        searchUser(formData.value.manager);
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch((err) => {});
}

async function submitForm() {
  formRef.value.validate().then(() => {
    if (dialogType.value == "add") {
      addSave();
    } else if (dialogType.value == "edit") {
      editSave();
    }
  });
}

const dialogClose = () => {
  dialogFormVisible.value = false;
};

const dialogOpen = (type: string, id: number) => {
  dialogFormVisible.value = true;
  dialogType.value = type;
  console.log(type);
  if (type == "add") {
    dialogTitle.value = "添加组织机构";
  } else if (type == "edit") {
    dialogTitle.value = "编辑组织机构";
    getInfo(id);
  }
};

const handleClose = () => {
  formRef.value.resetFields();
  formData.value = {
    id: 0,
    pid: 0,
    title: "",
    manager: "",
    sort: 0,
  };
  dialogFormVisible.value = false;
};

// 打开添加数据窗口
const emits = defineEmits(["getTable"]);
function getTableList() {
  getOptions();
  emits("getTable");
}

function getOptions() {
  getDepartmentOptionsApi().then((res) => {
    department_options.value = [{ id: 0, title: "顶级部门" }, ...res.data];
  });
}
onMounted(() => {
  getOptions();
});

defineExpose({
  dialogOpen,
  dialogClose,
  submitForm,
});
</script>

<style lang="scss">
.el-form-item {
  margin-bottom: 10px;
}
</style>

<style lang="scss" scoped></style>
